const { Service } = require("uni-cloud-router");
const uniID = require('uni-id');
const response=require("../utils/response.js");
const db = uniCloud.database({
	spaceId: 'b33db069-91a2-42ff-a831-31fbd5a04b97'
});
const dbCmd = db.command;
const collection=db.collection("uni-id-address");
const $ = db.command.aggregate;
module.exports = class AddressService extends Service {
  async add(){
		const ctx=this.ctx
		const dbJQL = uniCloud.databaseForJQL({
			event:ctx.envent,
			context:ctx.context
		})
		ctx.data.user_id=ctx.uid
		dbJQL.setUser({
			uid: ctx.uid, 
			role: ["admin"],
			permission: []
		})
		if(ctx.data.is_default){
			await dbJQL.collection('uni-id-address').where(`user_id == $cloudEnv_uid`).update({
				is_default:false
			})
		}
		const res=await dbJQL.collection('uni-id-address').add(ctx.data)
		if(res.code==0){
			return response.success(res.id)
		}else{
			return response.fail(res.message)
		}
  }
	async list(){
		const ctx=this.ctx
		const dbJQL = uniCloud.databaseForJQL({
			event:ctx.envent,
			context:ctx.context
		})
		ctx.data.user_id=ctx.uid
		dbJQL.setUser({
			uid: ctx.uid, 
			role: ["admin"],
			permission: []
		})
		const page_size=ctx.data.page_size||100
		const page_num=ctx.data.page_num||1
		const res=await dbJQL.collection('uni-id-address').where('user_id == $cloudEnv_uid').skip((page_num-1)*page_size).limit(page_size).get()
		if(res.code==0){
			return response.success(res.data)
		}else{
			return response.fail(res.message)
		}
	}
	async getOne(){
		const ctx=this.ctx
		const dbJQL = uniCloud.databaseForJQL({
			event:ctx.envent,
			context:ctx.context
		})
		ctx.data.user_id=ctx.uid
		dbJQL.setUser({
			uid: ctx.uid, 
			role: ["admin"],
			permission: []
		})
		const res=await dbJQL.collection('uni-id-address').where(`user_id==$cloudEnv_uid && _id=='${ctx.data.id}'`).get({
			getOne:true
		})
		if(res.code==0){
			return response.success(res.data)
		}else{
			return response.fail(res.message)
		}
	}
	async edit(){
		const ctx=this.ctx
		const dbJQL = uniCloud.databaseForJQL({
			event:ctx.envent,
			context:ctx.context
		})
		ctx.data.user_id=ctx.uid
		dbJQL.setUser({
			uid: ctx.uid, 
			role: ["admin"],
			permission: []
		})
		const id=ctx.data._id
		delete ctx.data._id
		if(ctx.data.is_default){
			const res=await dbJQL.collection('uni-id-address').where(`user_id == $cloudEnv_uid`).update({
				is_default:false
			})
			uniCloud.logger.log(res);
		}
		const res=await dbJQL.collection('uni-id-address').where(`user_id == $cloudEnv_uid && _id == '${id}'`).update(ctx.data)
		if(res.code==0){
			return response.success(res.updated)
		}else{
			return response.fail(res.message)
		}
	}
};